package org.gikolet.ch2.android.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;

import org.gikolet.ch2.data.Board;
import org.gikolet.ch2.data.ThreadHeader;
import org.gikolet.ch2.io.Formatter;
import org.gikolet.ch2.io.Storage;

public class LocalSubjectWriter {
	private Formatter<ThreadHeader> formatter;

	private BufferedWriter writer;

	public LocalSubjectWriter(Board board, Storage storage,
			Formatter<ThreadHeader> formatter, String charsetStr)
			throws FileNotFoundException, IOException {
		this(board, storage, formatter, Charset.forName(charsetStr));
	}

	public LocalSubjectWriter(Board board, Storage storage,
			Formatter<ThreadHeader> formatter, Charset charset)
			throws FileNotFoundException, IOException {

		this.formatter = formatter;

		File file = null;

		try {
			file = new File(storage.getDirectoryAndCreate(board), "subject.txt");

		} catch (IOException e) {
			e.printStackTrace();
		}

		if (file != null) {
			this.writer = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(file), charset));
		}
	}

	public void write(ThreadHeader subject) throws IOException {
		this.writer.append(formatter.format(subject)).append('\n');
	}

	public void close() throws IOException {
		Writer writer = this.writer;

		try {
			if (writer != null) {
				writer.flush();
			}

		} finally {
			try {
				if (writer != null) {
					writer.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
